package com.yf.course.modules.course.controller;

import cn.xfyun.api.RtasrClient;
import com.yf.course.modules.course.config.PropertiesConfig;
import cn.xfyun.model.response.rtasr.RtasrResponse;
import cn.xfyun.service.rta.AbstractRtasrWebSocketListener;
import com.yf.course.modules.course.utils.MicrophoneRecorder;
import com.yf.course.modules.course.utils.DashScopeChat;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import okio.ByteString;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sound.sampled.TargetDataLine;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import com.yf.course.modules.course.vo.ResultVo;

@RestController
@RequestMapping("/index")
public class RtasrClientApp {

	private static final String APP_ID = PropertiesConfig.getAppId();
	private static final String API_KEY = PropertiesConfig.getRtaAPIKey();
	private static final StringBuilder finalResult = new StringBuilder();

	// 新增变量，用于存储实时转写结果
	private StringBuilder realTimeResult = new StringBuilder();
	private boolean bl = false;

	@GetMapping("/start")
	public ResultVo<String> startRecording() {
		try {
			// 清空实时转写结果
			realTimeResult.setLength(0);
			sendByMicrophone();
			return ResultVo.success("开始录音成功");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultVo.failed("开始录音失败");
		}
	}
String last="";
	@GetMapping("/stop")
	public ResultVo<String> stopRecording() {
		bl = false;
		// 获取实时转写结果
		String currentResult = realTimeResult.toString();
		String temp=currentResult;
		currentResult=currentResult.substring(last.length());
		last=temp;
		if (!currentResult.isEmpty()) {
			// 调用 DashScope API 发送请求
			String response = DashScopeChat.callDashScopeAPI(currentResult+"100字以内");
			if (response != null) {
				int index = response.indexOf("</think>");
				if (index != -1) {
					response = response.substring(index + "</think>".length()).trim();
				}
				// 调用 Python 脚本并传递 response
				//String audioFilePath = callPythonScript(response);
				return ResultVo.success(response + " " );
			}
		}
		return ResultVo.success("停止录音成功，但实时转写结果为空");
	}

	// 新增接口，用于前端获取实时转写结果
	@GetMapping("/getRealTimeResult")
	public ResultVo<String> getRealTimeResult() {
		return ResultVo.success(realTimeResult.toString());
	}

	// 把转写结果解析为句子
	public static String getContent(String message) {
		boolean update = false;
		StringBuffer resultBuilder = new StringBuffer();
		resultBuilder.append(finalResult);
		try {
			JSONObject messageObj = JSON.parseObject(message);
			JSONObject cn = messageObj.getJSONObject("cn");
			JSONObject st = cn.getJSONObject("st");
			JSONArray rtArr = st.getJSONArray("rt");
			int bg = Integer.parseInt(st.getString("bg"));
			int ed = Integer.parseInt(st.getString("ed"));
			if (bg < ed) update = true;
			for (int i = 0; i < rtArr.size(); i++) {
				JSONObject rtArrObj = rtArr.getJSONObject(i);
				JSONArray wsArr = rtArrObj.getJSONArray("ws");
				for (int j = 0; j < wsArr.size(); j++) {
					JSONObject wsArrObj = wsArr.getJSONObject(j);
					JSONArray cwArr = wsArrObj.getJSONArray("cw");
					for (int k = 0; k < cwArr.size(); k++) {
						JSONObject cwArrObj = cwArr.getJSONObject(k);
						String wStr = cwArrObj.getString("w");
						resultBuilder.append(wStr);
						if (update) finalResult.append(wStr);
					}
				}
			}
		} catch (Exception e) {
			return message;
		}
		return resultBuilder.toString();
	}

	// 新增方法：实时麦克风输入
	public void sendByMicrophone() throws Exception {
		RtasrClient client = new RtasrClient.Builder()
				.signature(APP_ID, API_KEY).build();
		CountDownLatch latch = new CountDownLatch(1);

		// 创建麦克风录音器
		MicrophoneRecorder recorder = new MicrophoneRecorder();
		recorder.startRecording();

		WebSocket webSocket = client.newWebSocket(new AbstractRtasrWebSocketListener() {
			@Override
			public void onSuccess(WebSocket webSocket, String text) {
				RtasrResponse response = JSONObject.parseObject(text, RtasrResponse.class);
				String result = getContent(response.getData());
				System.out.println("实时结果: " + result);

				// 更新实时结果
				realTimeResult.setLength(0);
				realTimeResult.append(result);
			}

			@Override
			public void onFail(WebSocket webSocket, Throwable t, @Nullable Response response) {}

			@Override
			public void onBusinessFail(WebSocket webSocket, String text) {}

			@Override
			public void onClosed() {
				recorder.stopRecording();
				latch.countDown();
			}
		});

		// 实时发送音频流
		new Thread(() -> {
			try {
				bl = true;
				while (bl) {
					byte[] audioData = recorder.readAudioChunk();
					if (audioData.length == 0) break;
					webSocket.send(ByteString.of(audioData));
					Thread.sleep(40); // 严格40ms间隔
				}
				client.sendEnd(); // 发送结束标识
			} catch (Exception e) {
				e.printStackTrace();
			}
		}).start();

		latch.await();
	}

	// 调用 Python 脚本的方法
//	private String callPythonScript(String text) throws IOException, InterruptedException {
//		// 构建执行 Python 脚本的命令
//		List<String> command = new ArrayList<>();
//		// 指定虚拟环境中的 Python 解释器路径
//		command.add("E:\\szrcs\\.venv\\Scripts\\python.exe");
//		command.add("E:\\szrcs\\cs.py");
//		command.add(text);
//
//		// 创建 ProcessBuilder 对象并执行命令
//		ProcessBuilder processBuilder = new ProcessBuilder(command);
//		Process process = processBuilder.start();
//
//		// 获取脚本的标准输出流
//		BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//		String line;
//		String lastLine = null;
//		while ((line = reader.readLine()) != null) {
//			lastLine = line;
//		}
//
//		// 等待脚本执行完成并获取退出状态码
//		int exitCode = process.waitFor();
//		if (exitCode == 0) {
//			// 脚本执行成功，获取返回的地址
//			return lastLine;
//		} else {
//			// 脚本执行失败，打印错误信息
//			BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
//			StringBuilder errorOutput = new StringBuilder();
//			while ((line = errorReader.readLine()) != null) {
//				errorOutput.append(line).append("\n");
//			}
//			System.err.println("Python 脚本执行失败，退出状态码：" + exitCode);
//			System.err.println("错误信息：" + errorOutput.toString());
//			return null;
//		}
//	}
}